import { isMainThread, Worker, workerData, parentPort } from 'worker_threads';
import * as https from 'https';
import { EventEmitter } from 'events';

export function request(
  options: https.RequestOptions,
  body: Buffer,
  callback: (res: EventEmitter) => void,
) {
  if (!isMainThread) return;
  const worker = new Worker(__filename, {
    workerData: {
      options,
      body,
    },
  });
  const eventEmitter = new EventEmitter();
  worker.on('message', (res: { type: string; data: any }) => {
    eventEmitter.emit(res.type, res.data);
  });
  callback(eventEmitter);
}

if (!isMainThread) {
  const clientRequest = https.request(workerData.options, (res) => {
    res.on(
      'data',
      (data: Buffer) =>
        parentPort &&
        parentPort.postMessage({
          type: 'data',
          data: data ? data.toString('utf-8') : '',
        }),
    );
    res.on(
      'error',
      (err) =>
        parentPort &&
        parentPort.postMessage({
          type: 'error',
          data: err.message,
        }),
    );
    res.on(
      'end',
      (data: Buffer) =>
        parentPort &&
        parentPort.postMessage({
          type: 'end',
          data: data ? data.toString('utf-8') : null,
        }),
    );
  });
  clientRequest.on(
    'error',
    (error) =>
      parentPort &&
      parentPort.postMessage({
        type: 'error',
        error: error.message,
      }),
  );
  clientRequest.write(workerData.body);
  clientRequest.end();
}
